/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package be.ac.ua.comp.projectGPT.Jobs;

import be.ac.ua.comp.projectGPT.players.Consumer;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Executes several jobs in paralel.
 */
public class JobServer {

    ThreadPoolExecutor threadPoolExecutor;
    final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());

    public JobServer() {
        logger.info("Creating");
        final ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(
            5);
        threadPoolExecutor = new ThreadPoolExecutor(2,10,10,TimeUnit.SECONDS,queue);

    }

    public void stop() {
        threadPoolExecutor.shutdown();
    }

    /**
     * Starts a job by executing it in the threadPoolExecutor.
     * 
     * @param job The job to be executed.
     */
    public void startJob(Consumer consumer,Job job) {
        job.addObserver(consumer);
        if(job instanceof CallableJob) {
            logger.info("Callable job");
            try {
                Future<Boolean> future = threadPoolExecutor.submit((Callable) job);
                job.notifyObservers(String.valueOf(future.get()));
            } catch (InterruptedException ex) {
                logger.info("InterruptedException: "+ex.getLocalizedMessage());
            } catch (ExecutionException ex) {
                logger.info("ExecutorException: "+ex.getLocalizedMessage());
            }
        } else if (job instanceof RunnableJob) {
            logger.info("Runnable job");
            threadPoolExecutor.execute((Runnable) job);
            threadPoolExecutor.shutdown();
        }
    }

}
